package com.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.Role;
import com.mall.entity.RolePermission;
import com.mall.user.mapper.RoleMapper;
import com.mall.user.mapper.RolePermissionMapper;
import com.mall.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Role> save(Role role) {
        role.setIsDelete(0);
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        int insert = roleMapper.insert(role);
        if (insert != 0) {
            return roleMapper.selectList(null);
        }
        return null;
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    public List<Role> deleteRoleById(String roleId) {
        //根据角色id删除
        int i = roleMapper.deleteById(roleId);
        //根据角色删除角色权限中间表
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RolePermission::getRoleId,roleId);
        rolePermissionMapper.delete(wrapper);
        if (i > 0) {
            return roleMapper.selectList(null);
        }
        return null;
    }

    @Override
    public List<Role> selectRoleByName(String roleName) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(Role::getRoleName,roleName);
        return roleMapper.selectList(queryWrapper);
    }


}
